﻿#region Assembly mscorlib.dll, v4.0.30319
// C:\Archivos de programa\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using ImapX;
using System.Security.Authentication;
using ImapX.EmailParser;
using HTSwitchServerNamespace;
using HTSwitchMailHandlerNameSpace;
using OpenPop;
using OpenPop.Pop3;
using System.Runtime.InteropServices;

using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text.RegularExpressions;
using System.Diagnostics;

using CLoggerNamespace;

namespace HTSwitchMailHandlerNameSpace
{
    class MailHandler
    {
       
        ////////////////TO RECEIVE
        // connect to gmail server
        /*Aspose.Network.Imap.ImapClient imap = new Aspose.Network.Imap.ImapClient("imap.gmail.com", 993, "user@gmail.com", "pwd");
        imap.EnableSsl = true; // enable the SSL
        imap.SecurityMode = Aspose.Network.Imap.ImapSslSecurityMode.Implicit; // set security mode
        imap.Connect(true); // connect and login
        */        
        //Imap objImap =new Imap();
        //ImapClient objImapClient = new ImapClient("imap.gmail.com", 993, false, System.Security.Authentication.SslProtocols.None);        
        //EmailParser objEmailParser = new EmailParser("");

        
        //public Pop3Client objPopClient;

        #region CONTROL MAILS - OBTENCION, ENVIO Y ACTIVACION DE DATOS POSIBLE NUEVO CLIENTE USUARIO
        public void ControlMails(string strMailUser, string strMailPass,string strMailServer,string strTipoServicioMail)
        {
            
            //objImapClient = new ImapClient("imap.gmail.com", 993, false, System.Security.Authentication.SslProtocols.None);        
            CLogger.Append("Control de Mails: CONECTANDO...", CLogger.INFO);
            ////////// MAIL GMAIL///////////////////////////////////////////////////////////////
           // CLogger.Append("SERVER MAIL: " + strMailServer, CLogger.INFO);
            if (strMailServer.Contains("gmail.com"))
            {
                ImapClient objImapClient = new ImapClient(strMailServer, 993, true);
               // CLogger.Append("ENTRE A GMAIL", CLogger.INFO);
                try
                {
                    
                    //objImapClient = new ImapClient("imap.gmail.com", 993, true);
                   bool bConnect = objImapClient.Connection();                    
                    
                        CLogger.Append("CONECTADO A GMAIL", CLogger.INFO);

                    if (bConnect)
                    {
                        if (objImapClient.LogIn(strMailUser, strMailPass))
                        {
                            CLogger.Append("************************************Log-on IMAP GMAIL successful************************************", CLogger.INFO);

                            //string strFolder = objImapClient.SelectedFolder;

                            List<string> MailsObtenidos = ObtenerListaMails(strTipoServicioMail, objImapClient);
                                switch(strTipoServicioMail)
                                {
                                    case "WEBS":
                                        if (sendMailDatosUsuarioyActivacion(MailsObtenidos))
                                        {

                                            CLogger.Append("CHEKEO Y ENVIO DE MAILS *WEBS* CORRECTO", CLogger.INFO);
                                        }
                                        else
                                        {
                                            CLogger.Append("ATENCION ERROR KO: FALLO ENVIO DE DATOS *WEBS* DE ACTIVACION", CLogger.ERROR);
                                        }
                                    break;
                                    case "ML":
                                       /* if (sendMailDatosUsuarioML(MailsObtenidos))
                                        {

                                            CLogger.Append("CHEKEO Y ENVIO DE MAILS *ML* CORRECTO", CLogger.INFO);
                                        }
                                        else
                                        {
                                            CLogger.Append("ATENCION ERROR KO: FALLO ENVIO DE DATOS Usuario *ML*", CLogger.ERROR);
                                        }*/
                                    break;
                                    default:
                                      throw new Exception("TIPO DE SERVICIO NO INGRESADO");
                                   
                                }

                        }
                        else { CLogger.Append("ERROR MAIL LOGIN INCORRECTO.", CLogger.ERROR); }

                    }
                    else { CLogger.Append("ERROR MAIL NOT CONNECTED.", CLogger.ERROR); }

                }
                catch (Exception ex)
                {
                    CLogger.Append("ERROR OBTENCION Y ENVIO DE DATOS IMAP GMAIL:" + ex.Message, CLogger.ERROR);
                }
                finally
                {
                    CLogger.Append("Control de Mails: DESCONECTANDO IMAP GMAIL...", CLogger.INFO);
                    objImapClient.LogOut();
                    objImapClient.Disconnect();
                    CLogger.Append("********************************** DESCONECTADO successful*********************************", CLogger.INFO);
                }
            }
            else if (strMailServer.Contains("live.com"))   /////////////////////////////MAIL HOTMAIL ///////////////////////
            {
                try  //////////////////////////PRIMER MODO - CON DLL Pop3
                {
                   // Pop3Client objPopClient;
                   // objPopClient = new Pop3Client(strMailUser, strMailPass, strMailServer);
                    CLogger.Append("************************************Log-on POP3 HOTMAIL successful************************************", CLogger.INFO);
                    List<string> suids = new  List<string>();
                    List<OpenPop.Mime.Message> MensajesBox = FetchUnseenMessages(strMailServer, 995, true, strMailUser, strMailPass, suids);
                    
                    StringBuilder builder = new StringBuilder();
                    foreach (OpenPop.Mime.Message message in MensajesBox)
                    {
                        OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
                        if (plainText != null)
                        {
                            // We found some plaintext!
                            builder.Append(plainText.GetBodyAsText());
                        }
                        else
                        {
                            // Might include a part holding html instead
                            OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
                            if (html != null)
                            {
                                // We found some html!
                                builder.Append(html.GetBodyAsText());
                            }
                        }
                    }
                    CLogger.Append("MAILS HOTMAIL: " + builder.ToString(), CLogger.INFO);
                    
                }
                catch (Exception ex)
                {
                }
            }
        }

        #endregion
        #region   BUSCAR MAILS HOTMAILS - DEVUELVE LISTA MAILS

        public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                try
                {
                    // Connect to the server                
                    client.Connect(hostname, port, useSsl);

                    // Authenticate ourselves towards the server
                    client.Authenticate(username, password);

                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();

                    // We want to download all messages
                    List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);

                    // Messages are numbered in the interval: [1, messageCount]
                    // Ergo: message numbers are 1-based.
                    // Most servers give the latest message the highest number
                    for (int i = messageCount; i > 0; i--)
                    {
                        allMessages.Add(client.GetMessage(i));
                    }

                    // Now return the fetched messages
                    client.Disconnect();
                    return allMessages;
                }
                catch (Exception ex)
                {
                    throw ex;

                }
            }
        }
        public static List<OpenPop.Mime.Message> FetchUnseenMessages(string hostname, int port, bool useSsl, string username, string password, List<string> seenUids)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client clientH = new Pop3Client())
            {
                // Connect to the server
                try
                {
                    clientH.Connect(hostname, port, useSsl);

                    // Authenticate ourselves towards the server
                    clientH.Authenticate(username, password);

                    // Fetch all the current uids seen
                    List<string> uids = clientH.GetMessageUids();

                    // Create a list we can return with all new messages
                    List<OpenPop.Mime.Message> newMessages = new List<OpenPop.Mime.Message>();

                    // All the new messages not seen by the POP3 client
                    for (int i = 0; i < uids.Count; i++)
                    {
                        string currentUidOnServer = uids[i];
                        if (!seenUids.Contains(currentUidOnServer))
                        {
                            // We have not seen this message before.
                            // Download it and add this new uid to seen uids

                            // the uids list is in messageNumber order - meaning that the first
                            // uid in the list has messageNumber of 1, and the second has 
                            // messageNumber 2. Therefore we can fetch the message using
                            // i + 1 since messageNumber should be in range [1, messageCount]
                            OpenPop.Mime.Message unseenMessage = clientH.GetMessage(i + 1);

                            // Add the message to the new messages
                            newMessages.Add(unseenMessage);

                            // Add the uid to the seen uids, as it has now been seen
                            seenUids.Add(currentUidOnServer);
                        }
                    }

                    // Return our new found messages
                    clientH.Disconnect();
                    return newMessages;
                }
                catch (Exception ex)
                {
                    throw ex;

                }
                    
            }
        }
        #endregion

        #region OBTENER LISTA DE MAILS DE NUEVOS POSIBLES CLIENTES USUARIOS
        private List<string> ObtenerListaMails(string strTipoServicio, ImapClient objImapClient)
        {
            
          FolderCollection objFoldersCollected = objImapClient.Folders;
            
          //  MessageCollection objmessageCollection = objImapClient.Folders["WEBS"].Search("UNSEEN",true);
            List<string> strListMails = new List<string>();

           // listarFolders(objImapClient.GetFolders());    //Para DEBUG, lista las carpetas
            

            switch (strTipoServicio)
            {
                case "ML":
                    CLogger.Append("Obtener Lista Mails *ML*", CLogger.INFO);
                    foreach (ImapX.Message w in objImapClient.Folders["Mercadolibre"].Search("UNSEEN", true))
                    {
                        
                        //string decodedSubject = Encoding.GetEncoding(encoding).GetString(Convert.FromBase64String(w.Subject.Split('?')[3]));

                        w.Process();

                        string encoding = w.HtmlBody.ContentType.Split('=')[1];

                        string decodedBody = Encoding.GetEncoding(encoding).GetString(Convert.FromBase64String(w.HtmlBody.TextData));

                        CLogger.Append("MESSAGE: " + w.TextBody.TextData, CLogger.INFO);  //DEBUG DATA
                        CLogger.Append("MESSAGESTR: " + w.TextBody.ToString(), CLogger.INFO);  //DEBUG DATA
                        CLogger.Append("MESSAGE HTML: " + w.HtmlBody.TextData, CLogger.INFO);  //DEBUG HTML
                        CLogger.Append("MESSAGESTR HTML: " + w.HtmlBody.ToString(), CLogger.INFO);  //DEBUG HTML
                        CLogger.Append("encoding: " + encoding, CLogger.INFO);  //DEBUG DATA
                        CLogger.Append("decodedBody: " + decodedBody, CLogger.INFO);  //DEBUG DATA


                        if (w.Subject.Contains("¡Felicitaciones! Has vendido tu "))
                        {
                            CLogger.Append("*****************************************FoundMail ML VENTA***************************************", CLogger.INFO);     //DEBUG
                            if (w.TextBody.TextData.Contains("E-mail:"))
                            {
                                string strDataMail = w.TextBody.TextData;
                                 CLogger.Append("Mail: " + strDataMail, CLogger.INFO); //DEBUG

                                strListMails.Add(getUsersbyMailML(strDataMail));
                                w.SetFlag(ImapX.ImapFlags.SEEN);

                            }
                            else
                            {
                                throw new Exception("NO CONTIENE DATO DE BUSQUEDA");
                            }
                        }
                        else
                        {
                            throw new Exception("SUBJECT NOT FOUNDED");
                        }

                    }

                    break;

                case "WEBS":

                    CLogger.Append("Obtener Lista Mails *WEBS*", CLogger.INFO);

                    //foreach (ImapX.Message w in objImapClient.Folders["INBOX"].Search("UNSEEN", true))
                    foreach (ImapX.Message w in objImapClient.Folders["WEBS"].Search("UNSEEN", true))
                    {
                        w.Process();
                        //CLogger.Append("MESSAGE: " + w.TextBody.TextData, CLogger.INFO);  //DEBUG DATA
                        //CLogger.Append("MESSAGE HTML: " + w.HtmlBody.TextData, CLogger.INFO);  //DEBUG HTML

                        if (w.Subject == "Webs: FORM RESPONSE")
                        {
                            CLogger.Append("*****************************************FoundMail WEBS***************************************", CLogger.INFO);     //DEBUG

                            if (w.TextBody.TextData.Contains("Email Address ="))
                            {
                                string strDataMail = w.TextBody.TextData;
                                // CLogger.Append("Mail: " + strDataMail, CLogger.INFO);

                                strListMails.Add(getUsersbyMailWEBS(strDataMail));
                                w.SetFlag(ImapX.ImapFlags.SEEN);

                            }
                        }
                        else
                        {
                            throw new Exception("SUBJECT NOT FOUNDED");
                        }
                    }

                    break;

                default:
                    throw new Exception("TIPO DE SERVICIO NO INGRESADO");


            }
               

            return strListMails;
        }
        #endregion

        #region SEND ENVIAR DATOS DE USUARIO ML CONTROL

        private bool sendMailDatosUsuarioML(List<string> listMailsDatosUsuariosML)
        {
            string[] strClientHostDatos=new string[5];
            string strMensaje;
            string strUsuario;
            string strPassword;
            HTSwitchFlyersNameSpace.Fyers objFlyer = new HTSwitchFlyersNameSpace.Fyers();
            HTSwitchServerNamespace.HL7Control ObjContextControlHorseData = new HTSwitchServerNamespace.HL7Control(); 
            Random nRandom = new Random();
            int inNRandom;            

            try
            {
                foreach (string strMailUser in listMailsDatosUsuariosML)
                {

                    inNRandom = nRandom.Next(100, 999);
                    strPassword = "C" + System.DateTime.Today.Year.ToString() + inNRandom.ToString();

                    CLogger.Append("Enviando Mail de Activacion USUARIO ML to: " + strMailUser, CLogger.INFO);     ///DEBUG


                    strClientHostDatos[0] = "smtp.gmail.com";
                    strClientHostDatos[1] = "587";
                    strClientHostDatos[2] = strMailUser;///MAIL DE DESTINO A QUIEN VA IRIGIDO

                    strUsuario = strMailUser;
                    
                    CLogger.Append("Password: " + strPassword, CLogger.INFO);           ///DEBUG 

                    strMensaje=objFlyer.strArmarFlyerDatosUsuarioyPago(strUsuario,strPassword);
                    CLogger.Append("Mensaje de Mail: " + strMailUser, CLogger.INFO);        ///DEBUG

                    //strClientHost[2] = objGPSAndroidData.EMAIL;   //Dirección de mail a quien se le va a enviar
                    HTMailSenderNamespace.SimpleAsynchronousExample.MailGmailHTML(strClientHostDatos, "Datos Usuario", "controlesyseguimiento@gmail.com", strMensaje);
                   
                    //MAIL COPIA
                    strClientHostDatos[2] = "controlesyseguimiento@gmail.com";///MAIL DE DESTINO A QUIEN VA IRIGIDO
                    HTMailSenderNamespace.SimpleAsynchronousExample.MailGmailHTML(strClientHostDatos, "Datos Usuario Copia", "controlesyseguimiento@gmail.com", strMensaje);

                }
            }
            catch (Exception ex)
            {
                 //CLogger.Append("Error in MailSender: " + ex, CLogger.ERROR);
                 throw ex;
                
            }
            return true;
        
        }

        #endregion

        

        #region SEND ENVIAR MAIL DATOS DE USUARIO PARA ACTIVACION
        private bool sendMailDatosUsuarioyActivacion(List<string> listMailDatosUsuarios)
        {
            string[] strClientHostDatos=new string[5];
            string strMensaje;
            string strUsuario;
            string strPassword;
             HTSwitchFlyersNameSpace.Fyers objFlyer = new HTSwitchFlyersNameSpace.Fyers();
            HTSwitchServerNamespace.HL7Control ObjContextControlHorseData = new HTSwitchServerNamespace.HL7Control(); 
            Random nRandom = new Random();
            int inNRandom;
            

            try
            {
                foreach (string strMailUser in listMailDatosUsuarios)
                {

                    inNRandom = nRandom.Next(100, 999);
                    strPassword = "C" + System.DateTime.Today.Year.ToString() + inNRandom.ToString();

                    CLogger.Append("Enviando Mail de Activacion USUARIO WEBS to: " + strMailUser, CLogger.INFO);     ///DEBUG


                    strClientHostDatos[0] = "smtp.gmail.com";
                    strClientHostDatos[1] = "587";
                    strClientHostDatos[2] = strMailUser;///MAIL DE DESTINO A QUIEN VA IRIGIDO

                    strUsuario = strMailUser;
                    
                    CLogger.Append("Password: " + strPassword, CLogger.INFO);           ///DEBUG 

                    strMensaje=objFlyer.strArmarFlyerDatosUsuarioyPago(strUsuario,strPassword);
                    CLogger.Append("Mensaje de Mail: " + strMailUser, CLogger.INFO);        ///DEBUG

                    //strClientHost[2] = objGPSAndroidData.EMAIL;   //Dirección de mail a quien se le va a enviar
                    HTMailSenderNamespace.SimpleAsynchronousExample.MailGmailHTML(strClientHostDatos, "Datos Usuario", "controlesyseguimiento@gmail.com", strMensaje);
                   
                    //MAIL COPIA
                    strClientHostDatos[2] = "controlesyseguimiento@gmail.com";///MAIL DE DESTINO A QUIEN VA IRIGIDO
                    HTMailSenderNamespace.SimpleAsynchronousExample.MailGmailHTML(strClientHostDatos, "Datos Usuario Copia", "controlesyseguimiento@gmail.com", strMensaje);

                }
            }
            catch (Exception ex)
            {
                 //CLogger.Append("Error in MailSender: " + ex, CLogger.ERROR);
                 throw ex;
                
            }
            return true;
        }
        #endregion


        #region GET OBTENER USUARIO POR MAIL RECIBIDO ML
        public string getUsersbyMailML(string strTextMail)
        {
            int inContador;
            int inLengthClave;
            int inIndex;
            int inLast;
            string strMail;
            string strFraseClave = "E-mail: ";

            try
            {

                inLengthClave = strFraseClave.Length;
                CLogger.Append("LongitudText: " + inLengthClave, CLogger.INFO);
                inIndex = strTextMail.IndexOf(strFraseClave);
                //CLogger.Append("Index: " + inIndex, CLogger.INFO);
                inLast = strTextMail.LastIndexOf(strFraseClave);
                CLogger.Append("Last: " + inLast, CLogger.INFO);
                
                inContador = 1;
                while (strTextMail[inLast + inLengthClave + inContador] != '@')                
                {
                    inContador++;
                }

                strMail = strTextMail.Substring(inLast + inLengthClave, inContador - 1);                
                strMail= strMail + "mail.mercadolibre.com";
                 CLogger.Append("Mail*ML*ToSend: " + strMail, CLogger.INFO);
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR AL OBTENER DATOS DE USUARIO Y MAIL: " + ex.Message);
            }

            return strMail;
        }
        #endregion

        #region GET OBTENER USUARIO POR MAIL RECIBIDO WEBS
        public string getUsersbyMailWEBS(string strTextMail)
        {
            int inContador;
            int inLengthClave;
            int inIndex;
            int inLast;
            string strMail;
            string strFraseClave = "Email Address =";

            try
            {

                inLengthClave = strFraseClave.Length;
                //CLogger.Append("LongitudText: " + inLength, CLogger.INFO);

                inIndex = strTextMail.IndexOf(strFraseClave);

                //CLogger.Append("Index: " + inIndex, CLogger.INFO);
                inLast = strTextMail.LastIndexOf("Email Address =");
                //CLogger.Append("Last: " + inLast, CLogger.INFO);

                inContador = 1;
                while (strTextMail[inLast + inLengthClave + inContador] != '<')
                {
                    inContador++;
                }

                strMail = strTextMail.Substring(inLast + inLengthClave + 1, inContador - 1);

                // CLogger.Append("Mail*WEBS*ToSend: " + strMail, CLogger.INFO);
            }
            catch (Exception ex)
            {
                throw new Exception("ERROR AL OBTENER DATOS DE USUARIO Y MAIL: " + ex.Message);
            }

            return strMail;
        }
        #endregion

        #region LISTAR FOLDERS CARPETAS
        public void listarFolders(FolderCollection foldersL)
        {
                foreach (Folder myfolder in foldersL)
                {
                    CLogger.Append("Folder: " + myfolder.Name, CLogger.INFO);
                }
        }
        #endregion

        

        //////////////////////////////////////////DEPRECATED/////////////////////////////////////////////////////////////////////////

        #region DEPRACATED
        public bool YesOrNotMailParaActivar()
        {
            return true;
        }

       #endregion
        // Imap objImap = new Imap("imap.gmail.com",993,true,); //ssl: 0;12;48;192;240

       
         
    }
}
